package com.example.mytodo

import android.app.Activity
import android.content.ContentValues
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.widget.EditText
import android.widget.Toast
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.activity_new_todo.*
import java.util.logging.Handler

class NewTodoActivity : AppCompatActivity() {

    val TAG = "@@NewTodoActivity"

    lateinit var helper:DBHelper

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        helper = DBHelper(this,"todo",1)

        setContentView(R.layout.activity_new_todo)

        val userInputWatcher = object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                Log.i(TAG,"beforeTextChanged:$p0")
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                Log.i(TAG,"onTextChanged:$p0")
            }

            override fun afterTextChanged(p0: Editable?) {
                Log.i(TAG,"afterTextChanged:$p0")
            }

        }

        newtodo_edittext_todo.addTextChangedListener(userInputWatcher)

        newtodo_btn_submit.setOnClickListener {
            saveInput()
            Log.d(TAG, "saveInputed")

            val intent = Intent(this,MainActivity()::class.java)
            val mainAct : Activity = MainActivity()
            mainAct.finish()

            startActivity(intent)

        }

    }




    private fun saveInput(){
        val text = newtodo_edittext_todo.text.toString()

        saveInDb(text)
    }


    private fun saveInDb(text: String) {
        val db = helper.writableDatabase
        val item = Atodo(text,System.currentTimeMillis(),0)
        val values = ContentValues().apply {
            put(Atodo.T_TODOSTRING,item.todoString)
            put(Atodo.T_TIME,item.addtime)
            put(Atodo.T_STATE,item.state)
        }
        var rs = -1

        Log.d(TAG,"insert row id = $rs")
        rs = db.insert(Atodo.TABLE,null,values).toInt()
        println(rs)
        if(rs != -1 ){
            item.id = rs
        }

        Toast.makeText(this,if(rs < 0) "保存失败" else "保存成功" , Toast.LENGTH_LONG).show()

        // 置空
        setInputText("")
    }

    private fun setInputText(s: String) {
        findViewById<EditText>(R.id.newtodo_edittext_todo)?.setText(s)
    }


}